import 'dart:io';

import 'package:cgvc/data/basis_http.dart';
import 'package:cgvc/util/platform_util.dart';
import 'package:dio/dio.dart';
import 'package:flustars/flustars.dart';

final UpdateHttp http = UpdateHttp();

//检查版本更新
class UpdateHttp extends BasisHttp {
  @override
  void init() {
    options.baseUrl = 'https://www.pgyer.com/apiv2/';
    interceptors
      ..add(UpdateInterceptor())
      ..add(LogInterceptor(requestBody: true, responseBody: true));
  }
}

class UpdateInterceptor extends InterceptorsWrapper {
  @override
  onRequest(RequestOptions options) async {
    options.queryParameters['_api_key'] = 'f4d7dae2132cf8715c99ca79043deefb';
    options.queryParameters['appKey'] = Platform.isAndroid
        ? '9d5adc8a82bdcf48a905d8d5aa7f19e3'
        : '430e714ebb8fb7c3f2ab72fa5c5009dc';
    options.queryParameters['buildVersion'] =
        await PlatformUtil.getAppVersion();
    options.queryParameters['buildBuildVersion'] =
        await PlatformUtil.getBuildNumber();
    LogUtil.v(
        '---UpdateHttp-UpdateInterceptor-request--->url--> ${options.baseUrl}${options.path}  queryParameters:${options.queryParameters}');
    return options;
  }

  @override
  onResponse(Response response) {
    //拦截加了一层解析，response.data是接口返回的数据，也就是{"code":0,"message":"成功","data":{...}}
    //在这里先解析了，判断请求是否成功，成功的话把data拿出来再赋值给response.data，这样最上层拿到后只要做业务解析，不需要再解析code，message这一层
    ResponseData responseData = ResponseData.fromJson(response.data);
    LogUtil.v('UpdateHttp-UpdateInterceptor-onResponse:$responseData');
    if (responseData.success) {
      //这里为什么还要赋值回去呢？
      response.data = responseData.data;
      return http.resolve(response.data);
    } else {
      throw DioError();
    }
  }
}

class ResponseData {
  int code = 0;
  String message;
  dynamic data;

  bool get success => code == 0;

  ResponseData.fromJson(Map<String, dynamic> json) {
    code = json['code'];
    message = json['message'];
    data = json['data'];
  }

  @override
  String toString() {
    return '{code:$code, message:$message, data:$data}';
  }
}
